package com.jic.manager.controller.manage.conf;

import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.conf.api.manage.SysProvinceCityApi;
import com.jic.manager.entity.ProductComment;
import com.jic.manager.entity.Region;
import com.jic.manager.entity.SysProvinceCity;
import com.jic.conf.request.SysProvinceCityRequest;
import com.jic.conf.response.RegionResponse;
import com.jic.conf.response.SysProvinceCityResponse;
import com.jic.manager.enums.ResponseCode;
import com.jic.manager.exception.AppRuntimeException;
import com.jic.manager.service.ProductCommentService;
import com.jic.manager.service.RegionService;
import com.jic.manager.service.SysProvinceCityService;
import com.jic.enums.RedisKey;
import com.jic.manager.api.rest.ManagerStoreApi;
import com.jic.manager.response.MemMerchantInfoResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("all")
@Slf4j
@Api(tags = "省市区地址")
@RestController
@RequestMapping("/sysProvinceCity")
public class SysProvinceCityController  implements SysProvinceCityApi {

    @Resource
    private SysProvinceCityService sysProvinceCityService;
    @Resource
    private RedisClientTemplate redisClientTemplate;
    @Resource
    private RegionService regionService;
    @Resource
    private ManagerStoreApi managerStoreApi;
    @Resource
    private ProductCommentService productCommentService;

    @ApiOperation(value="查询省市区列表")
    @ResponseBody
    @Override
    public RestResult<List<SysProvinceCityResponse>> getSysProvinceCityList() {
        try{
            //判断redis中是否存在
            String cityList = redisClientTemplate.get(RedisKey.SYS_PROVINCE_CITY_LIST.getName());
            if (StringUtils.isNotEmpty(cityList)) return RestResult.success(JSONArray.parseObject(cityList,List.class));
            List<SysProvinceCity> sysProvinceCities = sysProvinceCityService.queryAll(new SysProvinceCity());
            List<SysProvinceCityResponse> resultList = new ArrayList<>();
            for (SysProvinceCity sysProvinceCity : sysProvinceCities) {
                if(sysProvinceCity == null){
                    continue;
                }
                SysProvinceCityResponse sysProvinceCityResponse = new SysProvinceCityResponse();
                Copy(sysProvinceCity, sysProvinceCityResponse);
                if (sysProvinceCityResponse.getPid() == 0 && sysProvinceCityResponse.getLevel() == 0) {
                    if (!exists(resultList, sysProvinceCityResponse)) {
                        resultList.add(sysProvinceCityResponse);
                    }
                }
            }
            findChildren(resultList, sysProvinceCities);
            redisClientTemplate.set(RedisKey.SYS_PROVINCE_CITY_LIST.getName(), JSONArray.toJSONString(resultList));
            return RestResult.success(resultList);
        }catch (Exception e){
            log.error("异常",e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION);
        }
    }

    @ApiOperation("根据ids查询销售区域")
    @ResponseBody
    @Override
    public RestResult<List<RegionResponse>> getRegionListByIds(@RequestBody  List<Long> ids) {
        try {
            List<RegionResponse> res = new ArrayList<>();
            if (CollectionUtils.isEmpty(ids)){
                List<Region> query = regionService.query(new Region());
                query.forEach(qu->{
                    RegionResponse regionResponse = new RegionResponse();
                    try {
                        Copy(qu,regionResponse);
                        RestResult<List<MemMerchantInfoResponse>> shopList = managerStoreApi.getShopList(new ArrayList<Long>() {{
                            add(regionResponse.getMerchantId());
                        }});
                        if(CollectionUtils.isNotEmpty(shopList.getData())){
                            MemMerchantInfoResponse memMerchantInfoResponse = shopList.getData().get(0);
                            regionResponse.setMerchantCode(memMerchantInfoResponse.getOrgNumber());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    res.add(regionResponse);
                });
                return RestResult.success(res);
            }
            ids.forEach(id->{
                Region region = regionService.queryByPrimaryKey(id);
                if (region != null){
                    RegionResponse regionResponse = new RegionResponse();
                    try {
                        Copy(region,regionResponse);
                        RestResult<List<MemMerchantInfoResponse>> shopList = managerStoreApi.getShopList(new ArrayList<Long>() {{
                            add(regionResponse.getMerchantId());
                        }});
                        if(CollectionUtils.isNotEmpty(shopList.getData())){
                             regionResponse.setMerchantCode(shopList.getData().get(0).getOrgNumber());
                        }
                    } catch (Exception e) {
                        log.error("异常",e);
                        throw new AppRuntimeException(ResponseCode.EXCEPTION);
                    }
                    res.add(regionResponse);
                }
            });
            return RestResult.success(res);
        }catch (Exception e){
            log.error("异常",e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION);
        }
    }

    @Override
    public RestResult<Long> getProductCommentCount(@RequestBody Long userId) {
        long count = productCommentService.queryCount(new ProductComment() {{
            setMemberId(userId);
        }});
        return RestResult.success(count);
    }


    /**
     *
     * @param source 被复制的实体类对象
     * @param to 复制完后的实体类对象
     * @throws Exception
     */
    public static void Copy(Object source, Object to) throws Exception {
        // 获取属性
        BeanInfo sourceBean = Introspector.getBeanInfo(source.getClass(), Object.class);
        PropertyDescriptor[] sourceProperty = sourceBean.getPropertyDescriptors();

        BeanInfo destBean = Introspector.getBeanInfo(to.getClass(), Object.class);
        PropertyDescriptor[] destProperty = destBean.getPropertyDescriptors();

        try {
            for (int i = 0; i < sourceProperty.length; i++) {

                for (int j = 0; j < destProperty.length; j++) {

                    if (sourceProperty[i].getName().equals(destProperty[j].getName())) {
                        // 调用source的getter方法和dest的setter方法
                        destProperty[j].getWriteMethod().invoke(to,sourceProperty[i].getReadMethod().invoke(source));
                        break;
                    }
                }
            }
        } catch (Exception e) {
            log.error("异常",e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION);
        }
    }

    /**
     * 判断当前权限是否添加过
     *
     * @param sysMenus
     * @param sysMenu
     * @return
     */
    private boolean exists(List<SysProvinceCityResponse> sysMenus, SysProvinceCityResponse sysMenu) {
        boolean exist = false;
        for (SysProvinceCityResponse menu : sysMenus) {
            if (menu.getId() == sysMenu.getId()) {
                exist = true;
            }
        }
        return exist;
    }

    private void findChildren(List<SysProvinceCityResponse> SysMenus, List<SysProvinceCity> menus) throws Exception {
        for (SysProvinceCityResponse SysMenu : SysMenus) {
            List<SysProvinceCityResponse> children = new ArrayList<>();
            for (SysProvinceCity menu : menus) {
//                if (menuType == 1 && menu.getAsInteger("type") == 2) {
//                    // 如果是获取类型不需要按钮，且菜单类型是按钮的，直接过滤掉
//                    continue;
//                }
                if (menu == null){
                    continue;
                }
                if (SysMenu.getId() == (menu.getPid())) {

//                    SysMenuVo sysMenuVo = (SysMenuVo) StrongParentSubclass.parentSubclass(menu, new SysMenuVo());
                    SysProvinceCityResponse sysProvinceCityResponse = new SysProvinceCityResponse();
                    Copy(menu, sysProvinceCityResponse);
                    if (!exists(children, sysProvinceCityResponse)) {
                        children.add(sysProvinceCityResponse);
                    }
                }
            }
            SysMenu.setChildren(children);
//            children.sort((o1, o2) -> o1.getSort().compareTo(o2.getSort()));
            findChildren(children, menus);
        }
    }


  /**
    * showdoc
    * @Author 王文斌
    * @catalog conf/
    * @title 分页查询城市列表
    * @description 分页查询城市列表
    * @method POST
    * @url /jic-conf/sysProvinceCity/getSysProvinceCityPageList
    * @param start 必选 int 当前页
    * @param limt 必选 int 每页条数
    * @param level 选填 int 级别-0省1市2县
    * @param name 选填 String 名称
    * @return {"code":"0000","data":{"rows":[{"code":"0","createTime":"2018-09-04 11:59:05","id":752149,"lat":"23.649577","level":2,"lng":"120.311052","name":"元长乡","pid":749957,"shortName":"元长","updateTime":"2018-09-04 11:59:05","zipCode":"000655"}],"total":3945},"message":""}
    * @return_param id int ID
    * @return_param name String 名称
    * @return_param level int 级别-0省1市2县
    * @return_param code String code
    * @return_param zipCode String 邮政编码
    * @return_param shortName String 简称
    * @return_param lng String 纵轴
    * @return_param lat String 横轴
    * @remark 这里是备注信息
    * @number 99
  */
    @PostMapping(value = "getSysProvinceCityPageList")
    public RestResult<PageResult<SysProvinceCity>> getSysProvinceCityPageList(@RequestBody SysProvinceCityRequest sysProvinceCityRequest){
        try {
            PageResult<SysProvinceCity> sysProvinceCityPageResult = sysProvinceCityService.queryPage(sysProvinceCityRequest);
            return new RestResult<PageResult<SysProvinceCity>>(){{
                setCode("0000");
                setData(sysProvinceCityPageResult);
            }};
        }catch (Exception e){
            log.error("异常",e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION);
        }
    }


    @ApiOperation("分类查询省市区列表")
    @PostMapping("getSysList")
    public RestResult<List<SysProvinceCity>> getSysList(@RequestBody SysProvinceCityRequest sysProvinceCityRequest){
        List<SysProvinceCity> sysProvinceCities = sysProvinceCityService.queryByLevel(Long.valueOf(sysProvinceCityRequest.getLevel()));
        return RestResult.success(sysProvinceCities);
    }


}
